<script setup>
import { onBeforeMount, ref } from 'vue';
import Card from './components/Card/Card.vue';
import Modal from './components/Modal/Modal.vue';
import { onClickOutside } from '@vueuse/core';

// Адрес заменен с 127.0.0.1 на localhost для устранения ошибки net::ERR_CONNECTION_REFUSED
const defaultURL = 'http://localhost:3000';
const searchParams = new URLSearchParams();

// Объявляем рефы
const personList = ref([]);
const inputValue = ref('');
const person = ref({});
const modalRef = ref();
const showModalToggler = ref(false);

const fetchDataHandler = async (url) => {
  await fetch(url)
    .then((res) => res.json())
    .then((data) => (personList.value = data))
    .catch((err) => console.error(err));
};

// Обновляем значение инпута с ключом term в searchParams, делаем fetch в зависимости от инпута
const onTouchEnterHandler = () => {
  if (searchParams.has("term")) {
    searchParams.delete('term');
  }

  searchParams.append('term', inputValue.value);

  inputValue != ''
    ? fetchDataHandler(`${defaultURL}?${searchParams}`)
    : fetchDataHandler(defaultURL);
};

const onClickShowModal = (personData) => {
  showModalToggler.value = true;
  person.value = personData;
};

const closeModal = () => {
  showModalToggler.value = false
}

// Использована сторонняя библиотека, хук импортирован оттуда
onClickOutside(modalRef, () => {
  showModalToggler.value = false
});

// Выполняет Fetch до рендера V-DOM
onBeforeMount(() => {
  fetchDataHandler(defaultURL);
});
</script>

<template>
  <div class="w-container-size mx-auto relative z-1">
    <div class="mt-16 mx-20">
      <div class="relative">
        <input
          v-model="inputValue"
          class="w-full h-12 pl-4 border border-solid border-secondary rounded-3xl outline-none focus:border-primary transition-all"
          type="text"
          @keyup.enter="onTouchEnterHandler()"
        />
        <img
          class="absolute top-3 right-6"
          src="./assets/img/search-icon.svg"
          alt="search-icon"
        />
      </div>

      <div class="mt-8 grid gap-6 grid-cols-3 mb-16">
        <Card
          v-for="person in personList"
          :key="personList.indexOf(person)"
          :name="person.name"
          :phoneNumber="person.phone"
          :email="person.email"
          @click="onClickShowModal(person)"
        />
        <div
          class="fixed top-0 left-0 z-10 w-full h-screen bg-modal-background/50"
          v-if="showModalToggler"
        >
          <Modal
            :name="person.name"
            :phone="person.phone"
            :email="person.email"
            :address="person.address"
            :department="person.department"
            :hireDate="person.hire_date"
            :positionName="person.position_name"
            :hideModal="closeModal"
            v-if="showModalToggler"
            ref="modalRef"
          />
        </div>
      </div>
    </div>
  </div>
</template>
